abbrvISI<-function(data.to.load,data.to.save){
#' Abbreviate journal titles
#' @param data.to.load (character) full path and name of input .bib file (including extension)
#' @param data.to.save (character) full path and name of output .bib file (including extension)
#' @author Joseph Henry \email{joseph.henry@@sydney.edu.au}
#' @date 16 December 2012
#' @note Internet connection required
#' Packages
  require (RCurl)
  require (stringr)
  require (XML)
  require (scrapeR)
  require (gdata)
  require (reshape)
#' Sub-functions
	TITLECASE <- function(x){
	  e1 <- tolower(substring(x,2,nchar(x)))
	  e2 <- toupper(substring(x,1,1))
	  e3 <- paste(e2,e1,sep="")
	  return (e3)
    }
	GETJOURNALNAMES <- function(input.){
	  o1 <- gsub(" |\t","", input.)
	  o2 <- substring(o1,1,7)
	  o3 <- grep("journal",o2)
	  return(list(j=o1[o3],l=o3))
	}
	CLEANJOURNALNAMES <- function(input.a,input.b) {
		o1 <- input.a[input.b[[2]]]
		o2 <- str_replace_all(o1,"(.*journal.*=.*\\{)(.*)(\\}.*)","\\2")
		o3 <- gsub("\\&"," and ", o2)
		o4 <- gsub("\\\\","",o3)
		return (o4)
	}
	ORDERJOURNALNAMES <- function(input.,journallines) {
		o1 <- input.
		o2 <- data.frame(O = 1:length(o1), J = o1, F=substring(o1,1,1), POS = journallines[[2]])
		o3 <- o2[order(o2$J),]
		return (o3)
	}
	UNIQUEJOURNALNAMES <- function(input.) {
		o1 <- input.
		o2 <- split(o1, o1$J)
		o3 <- sapply(o2, function (x) toString(x$POS))
		o4 <- data.frame(J=names(o3),OS = as.character(o3))
		o4[,1] <- gsub("  *"," ",o4[,1])
		return(o4)
	}
	GETNAMES <- function (input.) {
		base <- "http://images.webofknowledge.com/WOK46/help/WOS"
		tail <- "_abrvjt.html"
		o1 <- input.
		o2 <- substring(o1[,1],1,1)
		o3 <- split (o1,o2)
		o3names <- names(o3)
		  for(i in 1:length(o3names)){
		    a <- o3names[i]
		    if(length(unique(LETTERS%in%a))==2){	
			  z1 <- dir(getwd())
			  z2 <- paste(paste("WOK_abbreviation",toupper(a),sep="_"),".csv",sep="")
			 # if (length(grep(z2,z1))==0){
				  print(paste("Downloading data:",a))
				  a1 <- paste(base,"/",toupper(a),tail,sep="")
				  a2 <- getURL(a1)
				  a3 <- toHTML(a2)
				  a4 <- xmlValue(a3)
				  a5 <- strsplit(a4, " ")[[1]]
				  a6 <- strsplit(gsub(", "," ",toString(a5[239:length(a5)])),"</B><DT>")[[1]]
				  a6[1] <-  str_replace(a6[1],"(.*)(\\<DT\\>)(>)(.*)","\\4")
				  a6[length(a6)] <-  str_replace(a6[length(a6)],"(.*)(</B></DL>)(.*)","\\1")
				  a7 <- as.data.frame(colsplit(a6, split="\n<B><DD>\t", c("F","S")),stringsAsFactors = FALSE)
				  a7[,2] <- gsub("\n","",as.character(a7[,2]))
				  a71 <- grep("<D>",as.character(a7[,1]))
				  a72 <- as.character(a7[,1])
				  a72[a71] <- str_replace(a72[a71],"(.*)( *)(<D>)","\\1")
				  a8 <- data.frame(F=trim(as.character(a72)),S=trim(as.character(a7[,2])),stringsAsFactors = FALSE)
				  write.table(a8,z2,row.names=FALSE,sep=",")
				} else {
				print(paste("Previously downloaded data:",a))
		  #}
		}		
	  }
	}
	SHORTNAMES <- function (input.) {
	  o1 <-  input. #
	  o2 <- substring(o1[,1],1,1)
	  o3 <- split (o1,o2)
	  o3names <- names(o3)
	  namelist <- list()
	  for(i in 1:length(o3names)){
		if(length(unique(which(str_match(o3names,"[A-Z]")!="NA")%in%i))!=2){
		} else {
	    a <- o3names[i]
		if(length(unique(LETTERS%in%a))==2){	
		  z1 <- dir(getwd())
		  z2 <- paste(paste("WOK_abbreviation",toupper(a),sep="_"),".csv",sep="")
		  z3 <- paste(getwd(),z2,sep="/")
		  z4 <- read.csv(z3, header = TRUE)
		  z4[,1] <- gsub("&","AND",gsub("&amp;","&",as.character(z4[,1])))
		  z4[,2] <- gsub("&amp;","&",as.character(z4[,2]))
		  d0 <- o3[[i]]
		  z5 <- sapply( gsub(" ","",str_extract(toupper(as.character(d0$J)),"[0-9A-z ]*")), function (x) {
			d1 <- which(gsub(" ","",str_extract(z4[,1],"[0-9A-z ]*"))==x)
			if(length(d1)>1){
              d2 <- (d1[1])
			} else {
			  d2 <- d1			
			}
			return(z4[d2,])
			})
		  z51 <- matrix(ncol=2,byrow=T,unlist(unlist(z5)))
		  z521 <- sapply( gsub(" ","",str_extract(toupper(as.character(d0$J)),"[0-9A-z ]*")), function (x) {
			d1 <- which(gsub(" ","",str_extract(z4[,1],"[0-9A-z ]*"))==x)
			if(length(d1)>1){
              d2 <- (d1[1])
			} else {
			  d2 <- d1			
			}
			if(length(d1)==0){
			  d2 <- NA
			}
			return(d2)
			})
		  z53 <- as.numeric(which(is.na(z521)==FALSE))
		  if(length(unique(z53))!=0){			
		    z6 <- data.frame(raw=d0[z53,],full=z51[,1],abbrv=z51[,2])
		    namelist[[i]] <- z6
		  }
		}}
	 }
	 return( rbind.fill(namelist))
	}
	PREPAREBIB <- function(input.a,input.b,withdots,uppercase) {
	  a1 <-input.a
	  b1 <-input.b
	  b2 <- split(b1,b1[,1])
	  b3 <- lapply (b2, function (x) {
	   # x <- b2[[6]]
		x1 <- as.numeric(unlist(strsplit(as.character(x$raw.OS),", ")))
		x2 <- rep(x$abbrv,length(x1))
		x3 <- rep(x$raw.J,length(x1))
		x4 <- data.frame(L=x1,A=x2,O=x3)
		return(x4)
	  })
	  b4 <- rbind.fill(b3)

	  if(uppercase==TRUE){
	  	ap1 <-as.character(apply(b4,1, function(j) {
		ja <- as.character(j[2])
		jo <- toupper(as.character(j[3]))
		jo1 <- unlist(strsplit(jo , " "))
		ja1 <- unlist(strsplit(ja , " "))
		k <- which(jo1%in%ja1)
		if(length(k)!=0){
		  ja1[-k] <- paste(ja1[-k],".",sep="") 
		} else {
		 ja1 <- paste(ja1,".",sep="")
		}
		k1 <- gsub(", ", " ", toString(ja1))
		return(k1)
	  }))
	    ap2 <- b4$A
	  } else {
	    ap1 <-as.character(apply(b4,1, function(j) {
		ja <- as.character(j[2])
		jo <- toupper(as.character(j[3]))
		jo1 <- unlist(strsplit(jo , " "))
		ja1 <- unlist(strsplit(ja , " "))
		k <- which(jo1%in%ja1)
		ja1<-ifelse(nchar(ja1)!=1,TITLECASE(ja1),ja1)
		if(length(k)!=0){
		  ja1[-k] <- paste(ja1[-k],".",sep="")	 
		} else {
		 ja1 <- paste(ja1,".",sep="")
		}
		k1 <- gsub(", ", " ", toString(ja1))
		return(k1)
	  }))
        ap2<-as.character(sapply(as.character(b4$A),function(j) {	  
	      ap2.in <- unlist(strsplit(j, " "))
	      ap2.1 <- ifelse(nchar(ap2.in)!=1,TITLECASE(ap2.in),ap2.in)
		  ap2 <- gsub(", ", " ", toString(ap2.1 ))
		  return(ap2)
		}))
	  }
	  
	  if(withdots==FALSE){
	    ch1 <- ap2
	  } else {
	    ch1 <- ap1
      }
	  b5a <- paste("journal\t= {",ch1," (\\textbf{",b4$O,"})},",sep="")
	  b5b <- paste("journal\t= {",ch1,"},",sep="")	  
	  b51 <- which(ifelse(substring(ap2,1,1)==toupper(substring(b4$O,1,1)),TRUE,FALSE)==TRUE)
	  b6 <- data.frame(Abb=ap2,Old=b4$O)[b51,]
	  a2 <- a1
	  a2[b4$L[b51]] <- b5a[b51]
	  a3 <- a1
	  a3[b4$L[b51]] <- b5b[b51]
	  c1 <- list(a2,a3,unique(b1[,-2]))
	  return(c1)
	 }
#' Load
  input. <- readLines(data.to.load)
#' Clean
  journallines <- GETJOURNALNAMES(input.) # Line numbers for j articles
  print(1)
  journalnames <- CLEANJOURNALNAMES(input.,journallines) # Extract names
  print(2)
  journalord <- ORDERJOURNALNAMES(journalnames,journallines) # Order j alpha
  print(3)
  journalunique <- UNIQUEJOURNALNAMES(journalord) # Get unique j names
#' Do  
  #GETNAMES	(journalunique) # Download index
  journalnamematch <- SHORTNAMES (journalunique) # Match up names
  print(4)
  bibtowrite <- PREPAREBIB (input., journalnamematch,TRUE,FALSE) # Prepare bib
  print(5)
  writeLines(bibtowrite[[1]],gsub("[.]bib","_draft.bib",data.to.save)) # Update bib
  writeLines(bibtowrite[[2]],gsub("[.]bib","_final.bib",data.to.save)) # Update bib
  write.csv(bibtowrite[[3]],gsub("[.]bib","_check.csv",data.to.save),row.names=FALSE) # Checklist
}
